package com.music.mysongs.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.music.mysongs.R
import com.music.mysongs.adapter.MsgAdapter
import com.music.mysongs.data.ChatMsg
import com.music.mysongs.utils.BaseActivity
import com.music.mysongs.utils.myLog
import kotlinx.android.synthetic.main.activity_chat_room.*
import java.io.*
import java.net.Socket
import java.text.SimpleDateFormat
import java.util.*

class ChatRoomActivity : BaseActivity(), View.OnClickListener {
    private val mTag = "ChatRoomActivity"
    private val chatMsgList: MutableList<ChatMsg> = ArrayList()
    private val host: String = "192.168.43.164"//10.100.48.233
    private val port: Int = 7777
    private var adapter: MsgAdapter? = null
    private var socketRun: Socket? = null
    private var dis: BufferedReader? = null
    private var dos: PrintWriter? = null
    private var isRunning = false
    private val socketHandler: Handler = Handler {
        myLog("$mTag: obj=${it.obj}")
        if (it.obj != null) {
            @SuppressLint("SimpleDateFormat") val date =
                SimpleDateFormat("hh:mm:ss").format(
                    Date()
                )
            val sb = StringBuilder()
            sb.append(it.obj).append("\n" + date)
            val message = ChatMsg(sb.toString(), ChatMsg.TYPE_RECEIVED)
            chatMsgList.add(message)
            adapter?.notifyItemInserted(chatMsgList.size - 1)
            recyclerViewMsg_chatRoom.scrollToPosition(chatMsgList.size - 1)
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat_room)
        btnSend_chatRoom.setOnClickListener(this)
        runOnUiThread {
            recyclerViewMsg_chatRoom!!.layoutManager = LinearLayoutManager(this@ChatRoomActivity)
            recyclerViewMsg_chatRoom.adapter = MsgAdapter(chatMsgList)
        }
        Thread {
            try {
                socketRun = Socket(host, port)
                if (socketRun == null) {
                    myLog("$mTag: socket=$socketRun")
                } else {
                    isRunning = true
                    dis = BufferedReader(InputStreamReader(socketRun!!.getInputStream(), "UTF-8"))
                    dos = PrintWriter(
                        BufferedWriter(
                            OutputStreamWriter(
                                socketRun!!.getOutputStream()
                            )
                        ), true
                    )
                    Thread(MyReceive(), "接收线程").start()
                }
            } catch (e: Exception) {
                isRunning = false
                e.printStackTrace()
                Looper.prepare()
                myLog("$mTag: 连接服务器失败")
                Looper.loop()
                try {
                    socketRun?.close()
                } catch (e1: IOException) {
                    e1.printStackTrace()
                }
                finish()
            }
        }.start()
    }

    override fun onClick(view: View) {
        if (view.id == R.id.btnSend_chatRoom) {
            var content = editMsg_chatRoom.text.toString()
            val sb = StringBuilder()
            sb.append(content)
            content = sb.toString()
            if ("" != content) {
                val message = ChatMsg(content, ChatMsg.TYPE_SENT)
                chatMsgList.add(message)
                adapter?.notifyItemInserted(chatMsgList.size - 1)
                recyclerViewMsg_chatRoom.scrollToPosition(chatMsgList.size - 1)
                try {
                    dos?.println(content)
                    editMsg_chatRoom.setText("")
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            sb.delete(0, sb.length)
        }
    }

    internal inner class MyReceive : Runnable {
        override fun run() {
            var recMsg = ""
            while (isRunning) {
                try {
                    if (dis?.readLine().also { recMsg = it.toString() } != null) {
                        val msg = Message()
                        msg.obj = recMsg
                        socketHandler.sendMessage(msg)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}